using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// 区域类，表示一个可控制的区域
[System.Serializable]
public class Area
{
    public string name;           // 区域名称
    public string country;        // 控制国家
    public int archerAccount;     // 弓箭手数量
    public int infantryAccount;   // 步兵数量
    public int cavalryAccount;    // 骑兵数量
    public bool is_attacking;     // 是否处于攻击状态
    public Vector3 position;      // 区域位置

    // 获取区域的总兵力
    public int GetTotalSoldiers()
    {
        return archerAccount + infantryAccount;
    }
}

public class Area_Manager : MonoBehaviour
{
    // 单例模式
    public static Area_Manager Instance { get; private set; }

    // 所有区域列表
    [SerializeField]
    private List<Area> areas = new List<Area>();

    // 各国区域的字典
    private Dictionary<string, List<Area>> areasByCountry = new Dictionary<string, List<Area>>();

    [Header("士兵预制体")]
    public GameObject infantryPrefab;    // 步兵预制体
    public GameObject archerPrefab;      // 弓箭手预制体
    public GameObject cavalryPrefab;     // 骑兵预制体

    void Awake()
    {
        // 实现单例模式
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
        }

        // 初始化区域列表
        InitializeAreas();

        // 按国家分类区域
        OrganizeAreasByCountry();
    }

    // 初始化所有区域
    private void InitializeAreas()
    {
        // 吴国区域
        areas.Add(new Area { name = "East_君主府", country = "吴国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(18.88981f, -40.01f, 0f) });
        areas.Add(new Area { name = "East_村庄1", country = "吴国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(26.45709f, -51.54988f, 0f) });
        areas.Add(new Area { name = "East_村庄2", country = "吴国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(10.26407f, -51.42318f, 0f) });
        areas.Add(new Area { name = "East_铁匠铺", country = "吴国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(39.42f, -26.95f, 0f) });
        areas.Add(new Area { name = "East_墓地", country = "吴国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(4.889807f, -37.27554f, 0f) });

        // 魏国区域
        areas.Add(new Area { name = "North_君主府", country = "魏国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(-20.58905f, -3.924481f, 0f) });
        areas.Add(new Area { name = "North_军营", country = "魏国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(13.27f, -5.05f, 0f) });
        areas.Add(new Area { name = "North_村庄", country = "魏国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(-13.88f, -17.36f, 0f) });
        areas.Add(new Area { name = "North_墓地", country = "魏国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(-4.449743f, -6.120001f, 0f) });
        areas.Add(new Area { name = "North_商店", country = "魏国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(-44.46f, -14.74f, 0f) });

        // 蜀国区域
        areas.Add(new Area { name = "West_君主府", country = "蜀国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(-30.5f, -50.7f, 0f) });
        areas.Add(new Area { name = "West_村庄", country = "蜀国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(-36.16109f, -38.38079f, 0f) });
        areas.Add(new Area { name = "West_兵营", country = "蜀国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(-42.78436f, -59.06217f, 0f) });
        areas.Add(new Area { name = "West_墓地", country = "蜀国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(-59.57292f, -56.66331f, 0f) });
        areas.Add(new Area { name = "West_商店", country = "蜀国", archerAccount = 6, infantryAccount = 6, cavalryAccount = 6, is_attacking = false, position = new Vector3(-55.22218f, -34.43404f, 0f) });
    }

    // 按国家组织区域
    private void OrganizeAreasByCountry()
    {
        areasByCountry.Clear();

        foreach (var area in areas)
        {
            if (!areasByCountry.ContainsKey(area.country))
            {
                areasByCountry[area.country] = new List<Area>();
            }

            areasByCountry[area.country].Add(area);
        }
    }

    // 获取特定区域
    public Area GetArea(string areaName)
    {
        return areas.Find(a => a.name == areaName);
    }

    // 获取指定国家的所有区域
    public List<Area> GetAreasByCountry(string country)
    {
        if (areasByCountry.ContainsKey(country))
        {
            return areasByCountry[country];
        }

        return new List<Area>();
    }

    // 改变区域所属国家（占领）
    public void ChangeAreaOwnership(string areaName, string newCountry)
    {
        var area = GetArea(areaName);
        if (area == null)
        {
            Debug.LogError($"区域不存在: {areaName}");
            return;
        }

        string oldCountry = area.country;
        area.country = newCountry;

        // 更新国家区域字典
        if (areasByCountry.ContainsKey(oldCountry))
        {
            areasByCountry[oldCountry].Remove(area);
        }

        if (!areasByCountry.ContainsKey(newCountry))
        {
            areasByCountry[newCountry] = new List<Area>();
        }

        areasByCountry[newCountry].Add(area);

        Debug.Log($"区域 {areaName} 已从 {oldCountry} 转变为 {newCountry} 所有");
    }

    // 生成当前区域状态的JSON字符串
    public string GenerateAreasStatusJson()
    {
        string json = "[\n";

        for (int i = 0; i < areas.Count; i++)
        {
            var area = areas[i];
            json += $"  {{\n";
            json += $"    \"country\": \"{area.country}\",\n";
            json += $"    \"area\": \"{area.name}\",\n";
            json += $"    \"soldiers\": {area.GetTotalSoldiers()},\n";
            json += $"    \"e_position\": \"{area.position}\"\n";
            json += $"  }}";

            if (i < areas.Count - 1)
            {
                json += ",\n";
            }
            else
            {
                json += "\n";
            }
        }

        json += "]";
        return json;
    }

    // 导出特定国家的区域信息到JSON文件
    public void ExportCountryAreasToJson(string country, string folderPath, string fileName = "areaInformation.json")
    {
        List<Area> countryAreas = GetAreasByCountry(country);
        if (countryAreas.Count == 0)
        {
            Debug.LogWarning($"找不到属于 {country} 的区域");
            return;
        }

        // 生成JSON字符串
        string json = "[\n";
        for (int i = 0; i < countryAreas.Count; i++)
        {
            var area = countryAreas[i];
            json += $"  {{\n";
            json += $"    \"country\": \"{area.country}\",\n";
            json += $"    \"area\": \"{area.name}\",\n";
            json += $"    \"archerAccount\": {area.archerAccount},\n";
            json += $"    \"infantryAccount\": {area.infantryAccount},\n";
            json += $"    \"is_attacking\": {area.is_attacking.ToString().ToLower()},\n";
            json += $"    \"position\": \"{area.position}\"\n";
            json += $"  }}";

            if (i < countryAreas.Count - 1)
            {
                json += ",\n";
            }
            else
            {
                json += "\n";
            }
        }
        json += "]";

        // 确保目录存在
        System.IO.Directory.CreateDirectory(folderPath);
        string filePath = System.IO.Path.Combine(folderPath, fileName);

        // 写入文件
        try
        {
            System.IO.File.WriteAllText(filePath, json);
            Debug.Log($"成功将 {country} 的区域信息导出到: {filePath}");
        }
        catch (System.Exception e)
        {
            Debug.LogError($"导出区域信息时出错: {e.Message}");
        }

        // 刷新Asset数据库以显示新文件
#if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();
#endif
    }

    // 导出魏国区域信息到指定目录
    public void ExportWeiAreasInformation()
    {
        string folderPath = System.IO.Path.Combine(Application.dataPath, "Scripts/Wu_test/Wei/Wei_Information");
        ExportCountryAreasToJson("魏国", folderPath);
    }

    // 在区域生成士兵
    public void SpawnTroopsInArea(Area area)
    {
        if (area == null)
        {
            Debug.LogError("区域为空，无法生成士兵");
            return;
        }

        Debug.Log($"在区域 {area.name} 生成士兵，位置: {area.position}");

        // 转换国家名称为英文标签
        string countryTag = "";
        switch (area.country)
        {
            case "蜀国":
                countryTag = "Shu";
                break;
            case "魏国":
                countryTag = "Wei";
                break;
            case "吴国":
                countryTag = "Wu";
                break;
            default:
                Debug.LogError($"未知国家: {area.country}");
                return;
        }

        // 生成步兵
        for (int i = 0; i < area.infantryAccount; i++)
        {
            Vector3 spawnPosition = area.position + Random.insideUnitSphere * 2f;
            spawnPosition.z = 0; // 保持在2D平面
            GameObject infantry = Instantiate(infantryPrefab, spawnPosition, Quaternion.identity);
            ShiBing infantryScript = infantry.GetComponent<ShiBing>();
            if (infantryScript != null)
            {
                infantryScript.country = countryTag;
                infantryScript.formationIndex = i;
            }
        }

        // 生成弓箭手
        for (int i = 0; i < area.archerAccount; i++)
        {
            Vector3 spawnPosition = area.position + Random.insideUnitSphere * 2f;
            spawnPosition.z = 0;
            GameObject archer = Instantiate(archerPrefab, spawnPosition, Quaternion.identity);
            ShiBing archerScript = archer.GetComponent<ShiBing>();
            if (archerScript != null)
            {
                archerScript.country = countryTag;
                archerScript.formationIndex = area.infantryAccount + i;
            }
        }

        // 生成骑兵
        for (int i = 0; i < area.cavalryAccount; i++)
        {
            Vector3 spawnPosition = area.position + Random.insideUnitSphere * 2f;
            spawnPosition.z = 0;
            GameObject cavalry = Instantiate(cavalryPrefab, spawnPosition, Quaternion.identity);
            ShiBing cavalryScript = cavalry.GetComponent<ShiBing>();
            if (cavalryScript != null)
            {
                cavalryScript.country = countryTag;
                cavalryScript.formationIndex = area.infantryAccount + area.archerAccount + i;
            }
        }
    }

    // 生成所有区域的士兵
    public void SpawnAllTroops()
    {
        foreach (var area in areas)
        {
            SpawnTroopsInArea(area);
        }
    }
}


public class AreaTroopsManager : MonoBehaviour // 地区兵力管理类
{
    // 地区基本信息
    public string areaName;
    public enum AreaFaction { Wei, Shu, Wu, Neutral }
    public AreaFaction currentOwner = AreaFaction.Neutral;

    // 地区当前兵力
    [Header("当前兵力")]
    public int infantryCount = 10;   // 步兵数量
    public int archerCount = 10;     // 弓兵数量
    public int cavalryCount = 10;    // 骑兵数量

    [Header("调试信息")]
    [SerializeField] private string lastTroopTransaction; // 最后一次兵力调动记录
    [SerializeField] private string lastGeneralName;      // 最后调动兵力的将军

    /// <summary>
    /// 从地区请求调用兵力
    /// </summary>
    /// <param name="requestFaction">请求势力</param>
    /// <param name="requestedInfantry">请求的步兵数量</param>
    /// <param name="requestedArchers">请求的弓兵数量</param>
    /// <param name="requestedCavalry">请求的骑兵数量</param>
    /// <param name="generalName">将军名称（用于记录）</param>
    /// <returns>是否成功调用</returns>
    public bool RequestTroops(AreaFaction requestFaction, ref int requestedInfantry, ref int requestedArchers, ref int requestedCavalry, string generalName)
    {
        // 检查是否是己方区域
        if (currentOwner != requestFaction && currentOwner != AreaFaction.Neutral)
        {
            Debug.LogWarning($"地区 {areaName}: 无法从敌方区域调兵 (所属: {currentOwner})");
            return false;
        }

        // 检查请求是否超出可用兵力
        bool needAdjustment = false;

        if (requestedInfantry > infantryCount)
        {
            requestedInfantry = infantryCount;
            needAdjustment = true;
        }

        if (requestedArchers > archerCount)
        {
            requestedArchers = archerCount;
            needAdjustment = true;
        }

        if (requestedCavalry > cavalryCount)
        {
            requestedCavalry = cavalryCount;
            needAdjustment = true;
        }

        if (needAdjustment)
        {
            Debug.Log($"地区 {areaName}: 兵力请求已调整为可用最大值: {requestedInfantry}/{infantryCount} 步兵, {requestedArchers}/{archerCount} 弓兵, {requestedCavalry}/{cavalryCount} 骑兵");
        }

        // 执行兵力调用
        infantryCount -= requestedInfantry;
        archerCount -= requestedArchers;
        cavalryCount -= requestedCavalry;

        // 记录这次调动
        lastTroopTransaction = $"调出: {requestedInfantry} 步兵, {requestedArchers} 弓兵, {requestedCavalry} 骑兵";
        lastGeneralName = generalName;

        Debug.Log($"地区 {areaName}: {generalName} 调出兵力: {requestedInfantry} 步兵, {requestedArchers} 弓兵, {requestedCavalry} 骑兵, 剩余: {infantryCount} 步兵, {archerCount} 弓兵, {cavalryCount} 骑兵");
        return true;
    }

    /// <summary>
    /// 合并将军带来的兵力
    /// </summary>
    public void MergeTroops(AreaFaction troopFaction, int infantry, int archers, int cavalry, string generalName)
    {
        // 如果是己方区域，直接合并
        if (currentOwner == troopFaction || currentOwner == AreaFaction.Neutral)
        {
            // 如果是中立区域，被合并后变为该势力所属
            if (currentOwner == AreaFaction.Neutral)
            {
                currentOwner = troopFaction;
                Debug.Log($"地区 {areaName}: 被 {generalName} 设为 {troopFaction} 势力所属");
            }

            // 合并兵力
            infantryCount += infantry;
            archerCount += archers;
            cavalryCount += cavalry;

            // 记录这次合并
            lastTroopTransaction = $"合并: {infantry} 步兵, {archers} 弓兵, {cavalry} 骑兵";
            lastGeneralName = generalName;

            Debug.Log($"地区 {areaName}: {generalName} 合并兵力: {infantry} 步兵, {archers} 弓兵, {cavalry} 骑兵, 现有: {infantryCount} 步兵, {archerCount} 弓兵, {cavalryCount} 骑兵");
        }
        else
        {
            // 如果是敌方区域，可能触发战斗逻辑（暂不实现）
            Debug.LogWarning($"地区 {areaName}: {generalName} 尝试在敌方区域合并兵力, 可能触发战斗");
        }
    }
}